<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">
        当前位置：首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>服务卡管理</el-breadcrumb-item>
      <el-breadcrumb-item>服务卡配置</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <div slot="header">
        <span>基本信息</span>
      </div>
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="110px"
      >
        <el-form-item label="服务卡名称" prop="name">
          <el-input
            v-model="addForm.name"
            placeholder="请输入，将用于客户端服务卡名称展示（建议10字内）"
          ></el-input>
        </el-form-item>
        <el-form-item label="服务卡分类" prop="card_kind">
          <el-radio-group v-model="addForm.card_kind">
            <el-radio label="1">次数卡</el-radio>
            <el-radio label="2">时限卡</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="服务产品" prop="product_id">
          <el-select
            v-model="addForm.product_id"
            placeholder="请选择"
            filterable
            clearable
          >
            <el-option
              v-for="item in selectData.product"
              :key="item.id"
              :label="item.name + '【' + item.id + '】'"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="服务时长"
          v-show="addForm.card_kind == 2"
          :required="addForm.card_kind == 2"
        >
          <el-col :span="12">
            <el-form-item
              prop="time_long"
              :rules="
                addForm.card_kind == 2
                  ? [
                      { required: true, message: '请输入', trigger: 'blur' },
                      { type: 'number', message: '服务次数必须为数字值' }
                    ]
                  : []
              "
            >
              <el-input placeholder="请输入" v-model.number="addForm.time_long">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              prop="time_unit"
              :rules="
                addForm.card_kind == 2
                  ? [{ required: true, message: '请选择', trigger: 'change' }]
                  : []
              "
            >
              <el-select
                v-model="addForm.time_unit"
                placeholder="请选择时间单位"
              >
                <el-option label="分钟" value="1"></el-option>
                <el-option label="小时" value="2"></el-option>
                <el-option label="日" value="3"></el-option>
                <el-option label="月" value="4"></el-option>
                <el-option label="年" value="5"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <div v-show="addForm.card_kind == 1">
          <el-form-item
            label="服务卡类型"
            prop="card_type"
            :rules="
              addForm.card_kind == 1
                ? [{ required: true, message: '请选择', trigger: 'change' }]
                : []
            "
          >
            <el-select
              v-model="addForm.card_type"
              placeholder="请选择"
              filterable
              clearable
              @change="changeCardType"
            >
              <el-option key="0" label="单次卡" value="0"> </el-option>
              <el-option key="1" label="套卡" value="1"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="服务次数"
            prop="service_num"
            v-show="addForm.card_type == 1"
            :rules="
              addForm.card_type == 1
                ? [
                    { required: true, message: '请输入', trigger: 'blur' },
                    { type: 'number', message: '服务次数必须为数字值' }
                  ]
                : []
            "
          >
            <el-input
              v-model.number="addForm.service_num"
              placeholder="请输入，将用于客户端可用服务次数展示"
            ></el-input>
          </el-form-item>
          <el-form-item label="使用频率限制" v-show="addForm.card_type == 1">
            <el-col :span="12">
              <el-form-item prop="frequency_limit_way">
                <el-select
                  v-model="addForm.frequency_limit_way"
                  placeholder="请选择限制周期"
                >
                  <el-option value="1" label="每日"></el-option>
                  <el-option value="2" label="每周"></el-option>
                  <el-option value="3" label="每月"></el-option>
                  <el-option value="4" label="每年"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                prop="frequency_limit"
                :rules="
                  addForm.card_type == 1 && addForm.frequency_limit_way != ''
                    ? [{ type: 'number', message: '请输入数字' }]
                    : []
                "
              >
                <el-input
                  placeholder="请输入限制次数"
                  v-model.number="addForm.frequency_limit"
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-form-item>
        </div>
        <el-form-item label="有效期" required>
          <el-col :span="12">
            <el-form-item
              prop="period_num"
              v-show="addForm.unit != 4"
              :rules="
                addForm.unit != 4
                  ? [
                      { required: true, message: '请输入', trigger: 'blur' },
                      { type: 'number', message: '请输入数字' }
                    ]
                  : []
              "
            >
              <el-input
                placeholder="请输入，将用于客户端展示"
                v-model.number="addForm.period_num"
              >
              </el-input>
            </el-form-item>
            <el-form-item
              prop="period_date"
              v-show="addForm.unit == 4"
              :rules="
                addForm.unit == 4
                  ? [
                      {
                        required: true,
                        message: '请选择日期',
                        trigger: 'change'
                      }
                    ]
                  : []
              "
            >
              <el-date-picker
                type="date"
                placeholder="请选择"
                v-model="addForm.period_date"
                style="width: 100%"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="unit">
              <el-select v-model="addForm.unit" placeholder="请选择">
                <el-option value="1" label="日"></el-option>
                <el-option value="2" label="月"></el-option>
                <el-option value="3" label="年"></el-option>
                <el-option value="4" label="截止日期"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="使用方式" prop="use_way">
          <el-select
            v-model="addForm.use_way"
            placeholder="请选择使用方式"
            filterable
            clearable
          >
            <el-option key="1" label="预约使用" value="1"> </el-option>
            <el-option key="2" label="直接使用" value="2"> </el-option>
            <el-option key="3" label="在线服务" value="3"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适用范围说明" prop="apply_area">
          <el-input
            v-model="addForm.apply_area"
            placeholder="请输入，用于客户端服务卡使用范围说明"
          ></el-input>
        </el-form-item>
        <el-form-item label="限制使用区域" prop="area_limit_flag">
          <el-radio
            v-model="addForm.area_limit_flag"
            label="1"
            @change="changeLimit"
            >限制</el-radio
          >
          <el-radio
            v-model="addForm.area_limit_flag"
            label="0"
            @change="changeLimit"
            >不限制</el-radio
          >
        </el-form-item>
        <el-form-item
          label="区域限制方式"
          prop="area_limit_way"
          v-show="addForm.area_limit_flag == '1'"
          :rules="
            addForm.area_limit_flag == 1
              ? [{ required: true, message: '请选择', trigger: 'change' }]
              : []
          "
        >
          <el-select
            v-model="addForm.area_limit_way"
            placeholder="请选择区域限制方式"
            @change="changeRule"
          >
            <el-option value="1" label="按省份"></el-option>
            <el-option value="2" label="按城市"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="使用区域范围"
          prop="area_limit"
          v-show="addForm.area_limit_flag == '1'"
          :rules="
            addForm.area_limit_flag == 1
              ? [{ required: true, message: '请选择', trigger: 'change' }]
              : []
          "
        >
          <el-input
            placeholder="请选择区域范围"
            v-model="addForm.area_limit_name"
            readonly
          >
            <el-link type="primary" slot="append" @click="openRangeDialog"
              >选择区域</el-link
            >
          </el-input>
          <el-input v-model="addForm.area_limit" v-show="false"> </el-input>
        </el-form-item>
        <el-form-item label="使用区域描述" prop="area_limit_desc">
          <el-input
            v-model="addForm.area_limit_desc"
            placeholder="请输入，用于客户端服务卡使用区域说明"
          ></el-input>
        </el-form-item>
        <el-form-item label="服务标准" prop="service_standard">
          <el-input
            type="textarea"
            v-model="addForm.service_standard"
            show-word-limit
            maxlength="500"
            placeholder="请输入，用于客户端服务标准说明"
          ></el-input>
        </el-form-item>
        <el-form-item label="服务限制" prop="service_limit">
          <el-input
            type="textarea"
            v-model="addForm.service_limit"
            show-word-limit
            maxlength="500"
            placeholder="请输入，用于客户端服务限制说明"
          ></el-input>
        </el-form-item>
        <el-form-item label="服务须知" prop="service_instr">
          <el-input
            type="textarea"
            v-model="addForm.service_instr"
            show-word-limit
            maxlength="500"
            placeholder="请输入，用于客户端服务须知说明"
          ></el-input>
        </el-form-item>
        <el-form-item label="banner图" prop="banner_image" required>
          <el-upload
            :action="ossUrl"
            :headers="ossHeader"
            list-type="picture-card"
            :auto-upload="true"
            :limit="1"
            v-model="addForm.banner_image"
            :on-success="uploadSuccessMain"
            :on-preview="handlePictureCardPreviewMain"
            :on-remove="handleRemoveMain"
            :data="{ system: 'chongtai', module: '商品图片' }"
            :class="{ uoloadSty: showBtnImgMain, disUoloadSty: noneBtnImgMain }"
            :on-change="imgChangeMain"
            :before-upload="beforeUpload"
          >
            <i slot="default" class="el-icon-plus"></i>
            <div class="el-upload__tip" slot="tip">
              <ul style="margin-left: -25px; line-height: 20px; color: grey">
                <li>请上传jpg或png格式的图片，大小不超过2M</li>
                <li>上传的图片尺寸为750*400px，或与之等比例的图片</li>
              </ul>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="addForm.remark"
            show-word-limit
            maxlength="500"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="$router.push('/servicecard/ServicecardConfigure')">
            取 消
          </el-button>
          <el-button class="theme-background-color" @click="saveInfo"
            >保 存</el-button
          >
        </el-form-item>
      </el-form>

      <!-- 选择省份区域对话框 -->
      <chooseMultipleProvince
        :provinceVisible.sync="provinceVisible"
        :checkedRanges="checkedRanges"
        @showProvincesData="updateRanges"
      ></chooseMultipleProvince>

      <!-- 选择城市区域对话框 -->
      <ChooseMultipleCity
        :cityVisible.sync="cityVisible"
        :checkedRanges="checkedRanges"
        @showCitiesData="updateRanges"
      ></ChooseMultipleCity>

      <!-- 放大图片弹窗 -->
      <el-dialog :visible.sync="dialogVisible" width="45%">
        <img width="100%" :src="dialogImageUrl" alt="" />
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import chooseMultipleProvince from '../region/ChooseMultipleProvince.vue'
import ChooseMultipleCity from '../region/ChooseMultipleCity.vue'
export default {
  components: { chooseMultipleProvince, ChooseMultipleCity },
  data() {
    var imageValidator = (rule, value, callback) => {
      if (
        this.addForm.banner_image === undefined ||
        this.addForm.banner_image === ''
      ) {
        callback(new Error('请上传商品主图'))
      }
      callback()
    }
    return {
      addForm: {
        name: '',
        card_type: '',
        product_id: '',
        service_num: '',
        frequency_limit_way: '',
        frequency_limit: '',
        period: '',
        period_num: '',
        period_date: '',
        unit: '',
        apply_area: '',
        area_limit_flag: '0',
        area_limit_way: '',
        area_limit: '',
        area_limit_desc: '全国',
        service_standard: '',
        service_limit: '',
        service_instr: '',
        banner_image: '',
        use_way: '',
        card_kind: '1',
        time_long: '',
        time_unit: '',
        remark: ''
      },
      addFormRules: {
        name: [
          { required: true, message: '请输入', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        // card_type: [{ required: true, message: '请选择', trigger: 'change' }],
        product_id: [{ required: true, message: '请选择', trigger: 'change' }],
        unit: [{ required: true, message: '请选择', trigger: 'change' }],
        apply_area: [{ required: true, message: '请输入', trigger: 'blur' }],
        area_limit_flag: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        area_limit_desc: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        service_standard: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        service_limit: [{ required: true, message: '请输入', trigger: 'blur' }],
        banner_image: [{ validator: imageValidator }],
        use_way: [{ required: true, message: '请选择', trigger: 'change' }],
        card_kind: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      selectData: [],

      // 省市控件勾选用的数据
      checkedRanges: [],
      provinceVisible: false,
      cityVisible: false,

      // banner图
      dialogImageUrl: '',
      dialogVisible: false,
      ossUrl: this.GLOBAL.ossUrl,
      ossHeader: this.GLOBAL.ossHeader,
      showBtnImgMain: true,
      noneBtnImgMain: false
    }
  },
  created() {
    this.getSelectData()
  },
  methods: {
    async getSelectData() {
      const { data: res } = await this.$http.post('/admin/data/find', {
        code: 'product'
      })
      // 返回结果
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.selectData = res.data
    },
    changeLimit(val) {
      console.log(val)
      if (val == 0) {
        this.addForm.area_limit = ''
        this.addForm.area_limit_name = ''
        this.addForm.area_limit_desc = '全国'
      } else {
        this.addForm.area_limit_desc = ''
      }
    },
    changeCardType(val) {
      console.log(val)
      if (val == 0) {
        this.addForm.service_num = 1
      } else {
        this.addForm.service_num = ''
      }
      this.addForm.frequency_limit_way = ''
      this.addForm.frequency_limit = ''
    },
    updateRanges(data) {
      this.addForm.area_limit = data.code.join(',')
      this.addForm.area_limit_name = data.name.join(',')
      this.addForm.area_limit_desc = this.addForm.area_limit_name
      // console.log(data)
    },
    changeRule() {
      this.addForm.area_limit_name = ''
      this.addForm.area_limit = ''
      this.addForm.area_limit_desc = ''
    },
    openRangeDialog() {
      if (this.addForm.area_limit_way === '') {
        this.$message({
          message: '请先选择区域限制方式',
          type: 'warning'
        })
      } else {
        this.provinceRangeDialogVisible = true
        if (parseInt(this.addForm.area_limit_way) === 1) {
          this.provinceVisible = true
        } else {
          this.cityVisible = true
        }
        // console.log(this.addForm.area_limit)
        this.checkedRanges = this.addForm.area_limit
          ? this.addForm.area_limit.split(',')
          : []
      }
    },
    saveInfo() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return
        this.addForm.period = this.period
        console.log(this.addForm)

        const { data: res } = await this.$http.post(
          '/admin/service_card_config/add',
          this.addForm
        )
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.$router.push('/servicecard/ServicecardConfigure')
      })
    },
    uploadSuccessMain(response, file, fileList) {
      if (Number.parseInt(response.code) === 10001) {
        this.addForm.banner_image = response.data.url
      } else {
        this.$message.error(response.message)
        var a = fileList.findIndex((item) => item.uid === file.uid)
        if (a !== -1) {
          fileList.splice(a, 1)
        }
      }
      // console.log(this.addForm.banner_image)
    },
    //   删除图片
    handleRemoveMain(file, fileList) {
      this.addForm.banner_image = ''
      this.noneBtnImgMain = fileList.length === 1
    },
    // 放大图片
    handlePictureCardPreviewMain(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    imgChangeMain(file, fileList) {
      this.noneBtnImgMain = fileList.length === 1
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG/PNG 格式!')
      } else if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  },
  computed: {
    period() {
      return this.addForm.unit == 4
        ? this.addForm.period_date
        : this.addForm.period_num
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 80%;
  margin-left: 15px;
  .el-select {
    width: 100%;
  }
}
/deep/ .uoloadSty .el-upload--picture-card {
  width: 230px;
  display: true;
}
/deep/ .disUoloadSty .el-upload--picture-card {
  display: none; /* 上传按钮隐藏 */
}
/deep/ .uoloadSty .el-upload-list__item {
  width: 230px;
}
</style>
